<template>
  <div>
    <a-card class="card" title="商品设置">
      <a-spin :spinning="confirmLoading">
        <j-form-container :disabled="formDisabled">
          <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
            <a-row>
              <a-col :span="24">
                <a-form-model-item label="商品全称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                  <a-input v-model="model.name" placeholder="请输入商品全称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="商品简称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shortName">
                  <a-input v-model="model.shortName" placeholder="请输入商品简称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-modal width="700px" :centered="true" title="商品库" :visible="shopLibrary" @ok="shopLibraryOk"
                @cancel="shopLibraryCancel">
                <a-table size="middle" :loading="table" bordered rowKey="id" :columns="libraryColumns"
                  :pagination="ipagination" :dataSource="libraryData" @change="changePage"
                  :rowSelection="{ selectedRowKeys: selectedRowKeysArrey, onChange: onSelectChange, type: 'radio' }">
                  <template slot="imgSlot" slot-scope="text">
                    <img style="width: 80px; height: 80px" :src="text" alt="">
                  </template>
                </a-table>
              </a-modal>
              <a-col :span="24">
                <a-form-model-item label="商品原价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="originalPrice">
                  <a-input-number v-model="model.originalPrice" placeholder="请输入商品原价" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="会员价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="presentPrice">
                  <a-input-number v-model="model.presentPrice" placeholder="请输入商品现价" style="width: 100%">
                  </a-input-number>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="24">
                <a-form-model-item label="商品代码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
                  <a-input v-model="model.code" placeholder="请输入商品代码"></a-input>
                </a-form-model-item>
              </a-col> -->
              <!-- <a-col :span="24">
                <a-form-model-item label="商品图片(1:1)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="picture">
                  <j-image-upload biz-path="laile2/goods" acceptFormat="image/png, image/jpeg" v-model="model.picture">
                  </j-image-upload>
                </a-form-model-item>
              </a-col> -->
              <a-col :span="24">
                <a-form-model-item label="商品图片(1:1)" disabled :labelCol="labelCol" :wrapperCol="wrapperCol"
                  prop="picture">
                  <j-image-upload isMultiple v-model="model.picture"></j-image-upload>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="起售数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesQuantity">
                  <a-input-number v-model="model.salesQuantity" placeholder="请输入起售数量，默认1" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="商品一级分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="kategorieId">
                  <a-tree-select @change="handleTreeSelectChange" :treeDefaultExpandAll='true' :tree-data="sortLista"
                    :replaceFields="replaceFieldsa" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    allow-clear>
                  </a-tree-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="商品二级分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="secondary">
                  <a-tree-select :treeDefaultExpandAll='true' :tree-data="secondary" v-model="model.kategorieId"
                    :replaceFields="replaceFieldsa" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    allow-clear>
                  </a-tree-select>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="24">
                <a-form-model-item label="店内分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sorts">
                  <a-tree-select :treeDefaultExpandAll='true' :tree-data="sortLista2" v-model="model.sorts" :replaceFields="replaceFieldsa" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" allow-clear>
                  </a-tree-select>
                </a-form-model-item>
              </a-col> -->
              <!-- <a-col :span="24">
                <a-form-model-item label="商品供应商" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select :treeDefaultExpandAll='true' :tree-data="sortListb" v-model="model.goodBrand" :replaceFields="replaceFieldsb" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" allow-clear>
                  </a-tree-select>
                </a-form-model-item>
              </a-col> -->
              <a-col :span="24">
                <a-form-model-item label="商品描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="description">
                  <a-input v-model="model.description" placeholder="请输入商品描述"></a-input>
                </a-form-model-item>
              </a-col>
              <!--              <a-col :span="24">
                <a-form-model-item label="商品简单描述" :labelCol="labelCol" :wrapperCol="wrapperCol"
                                   prop="shortDescription">
                  <a-input v-model="model.shortDescription" placeholder="请输入商品简单描述"></a-input>
                </a-form-model-item>
              </a-col>-->
              <a-col :span="24">
                <a-form-model-item label="商品上下架状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">
                  <j-dict-select-tag type="list" v-model="model.status" dictCode="mk_goods_status"
                    placeholder="请选择商品上下架状态" />
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="24">
                <a-form-model-item label="商品是否是拼团商品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enableGroup">
                  <j-dict-select-tag type="list" v-model="model.enableGroup" dictCode="is_group" placeholder="请选择商品拼团状态" />
                </a-form-model-item>
              </a-col> -->
              <!--              <a-col :span="24">
                <a-form-model-item label="是否首页展示" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isIndex">
                  <j-dict-select-tag type="list" v-model="model.isIndex" dictCode="mk_whether"
                    placeholder="请选择是否首页展示" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="是否热门商品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isHot">
                  <j-dict-select-tag type="list" v-model="model.isHot" dictCode="mk_whether" placeholder="请选择是否热门商品" />
                </a-form-model-item> 
              </a-col>-->
              <!--             TODO 前端增加限制-->
              <a-col :span="24">
                <a-form-model-item label="是否单点不送" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="oneNoDelivery">
                  <j-dict-select-tag type="list" v-model="model.oneNoDelivery" dictCode="mk_whether"
                    placeholder="请选择是否单点不送" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="排序" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sort">
                  <a-input-number v-model="model.sort" placeholder="请输入排序，默认0" style="width: 100%" />
                </a-form-model-item>
              </a-col>

            </a-row>
            <!-- table -->
            <a-card title="商品规格设置">
              <form :autoFormCreate="(form) => this.form = form" prop="goodsSpecificationsVoList">
                <a-table v-model="model.goodsSpecificationsVoList" :columns="columns2"
                  :dataSource="goodsSpecificationsVoList" :rules="validatorRules" :pagination="false">

                  <template
                    v-for="(col, i) in ['nameSku', 'imgSlot', 'priceSku', 'srcPriceSku', 'weightGSku', 'stockSku', 'packFeeSku']"
                    :slot="col" slot-scope="text, record, index " prop="col">
                    <a-input :key="col" v-if="record.editable && col !== 'pictureSku'" style="margin: -5px 0"
                      :value="text" :v-model="columns2[i].key" :placeholder="columns2[i].title"
                      @change="e => handleChange2(e.target.value, record.key, col)" />
                    <template v-else>{{ text }}</template>
                  </template>

                  <template slot="imgSlot" slot-scope="text,scope,index">
                    <j-image-upload :value="scope.pictureSku" biz-path="laile2/goods" :imgIndex="index"
                      acceptFormat="image/png, image/jpeg" @change="uploadImgs"></j-image-upload>
                  </template>
                  <template slot="operation" slot-scope="text, record, index">
                    <template v-if="record.editable">
                      <span v-if="record.isNew">
                        <a @click="saveRow2(record.key)">添加</a>
                        <a-divider type="vertical" />
                        <a-popconfirm title="是否要删除此行？" @confirm="remove2(record.key)">
                          <a>删除</a>
                        </a-popconfirm>
                      </span>
                      <span v-else>
                        <a @click="saveRow2(record.key)">保存</a>
                        <a-divider type="vertical" />
                        <a @click="cancel2(record.key)">取消</a>
                      </span>
                    </template>
                    <span v-else>
                      <a @click="toggle2(record.key)">编辑</a>
                      <a-divider type="vertical" />
                      <a-popconfirm title="是否要删除此行？" @confirm="remove2(record.key)">
                        <a>删除</a>
                      </a-popconfirm>
                    </span>
                  </template>
                </a-table>
                <a-button style="width: 100%; margin-top: 16px; margin-bottom: 8px" type="dashed" icon="plus"
                  @click="newMember2">新增规格
                </a-button>
              </form>
            </a-card>
            <!-- table -->
            <a-card title="商品属性设置">
              <form :autoFormCreate="(form) => this.form = form" prop="goodsAttributeVoList">
                <a-table v-model="model.goodsAttributeVoList" :columns="columns1" :dataSource="goodsAttributeVoList"
                  :pagination="false">
                  <template v-for="(col, i) in ['nameSku', 'valueSku']" :slot="col" slot-scope="text, record, index">
                    <a-input :key="col" v-if="record.editable" style="margin: -5px 0" :value="text"
                      :v-model="columns1[i].key" :placeholder="columns1[i].title"
                      @change="e => handleChange1(e.target.value, record.key, col)" />
                    <template v-else>{{ text }}</template>
                  </template>
                  <template slot="tagSlot" slot-scope="text,scope,index">
                    <div>
                      <template v-for="(tag, index) in scope.valueSku">
                        <a-input v-if="index == currentTagIndex" ref="input" type="text" size="small"
                          :style="{ width: '190px' }" :value="tag" @change="handleInputChange"
                          @blur="handleInputEditConfirm(scope, tag, index)"
                          @keyup.enter="handleInputEditConfirm(scope, tag, index)" />
                        <a-tag v-else :key="tag" :closable="true" @close="() => removeTag(scope, tag)"
                          @click="editTag(tag, index)">
                          {{ tag }}
                        </a-tag>
                      </template>
                      <a-input v-if="inputVisible && index == currentNameIndex" ref="input" type="text" size="small"
                        :style="{ width: '100px' }" :value="inputValue" @change="handleInputChange"
                        @blur="handleInputConfirm(scope)" @keyup.enter="handleInputConfirm(scope)" />
                      <a-tag v-else style="background: #fff; borderStyle: dashed;" @click="showInput(scope, index)">
                        <a-icon type="plus" />
                        新建
                      </a-tag>
                    </div>
                  </template>
                  <template slot="operation" slot-scope="text, record, index">
                    <template v-if="record.editable">
                      <span v-if="record.isNew">
                        <a @click="saveRow1(record.key)">添加</a>
                        <a-divider type="vertical" />
                        <a-popconfirm title="是否要删除此行？" @confirm="remove1(record.key)">
                          <a>删除</a>
                        </a-popconfirm>
                      </span>
                      <span v-else>
                        <a @click="saveRow1(record.key)">保存</a>
                        <a-divider type="vertical" />
                        <a @click="cancel1(record.key)">取消</a>
                      </span>
                    </template>
                    <span v-else>
                      <a @click="toggle1(record.key)">编辑</a>
                      <a-divider type="vertical" />
                      <a-popconfirm title="是否要删除此行？" @confirm="remove1(record.key)">
                        <a>删除</a>
                      </a-popconfirm>
                    </span>
                  </template>
                </a-table>
                <a-button style="width: 100%; margin-top: 16px; margin-bottom: 8px" type="dashed" icon="plus"
                  @click="newMember1">新增属性
                </a-button>
              </form>
            </a-card>
            <a-card title="商品详情">
              <div style="border: 1px solid #ccc;">
                <Toolbar style="border-bottom: 1px /solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
                  :mode="mode" />
                <Editor style="height: 500px; overflow-y: hidden;" v-model="model.goodDetail"
                  :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
              </div>
            </a-card>
          </a-form-model>
        </j-form-container>
      </a-spin>
    </a-card>
  </div>
</template>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<script>
import { ACCESS_TOKEN } from '@/store/mutation-types'
import store from '@/store'

import Vue from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'

import FooterToolBar from '@/components/tools/FooterToolBar'
import { postAction, uploadAction } from '../../../api/manage'

export default {
  name: 'GoodsBasicForm',
  components: { Editor, Toolbar },
  props: {
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      kategorield: '',
      goodBrand: '',
      editor: null,
      //富文本
      sortListb: [],
      toolbarConfig: {
        excludeKeys: ['fullScreen', 'code', 'group-video', 'codeBlock', 'bulletedList', 'numberedList', 'blockquote', 'bold', 'italic', 'todo', 'insertImage', 'insertLink', 'emotion'] // 此处不需要的工具栏选项
      },
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          //配置上传图片
          uploadImage: {
            customUpload: this.uploadImg
          }
        }
      },
      mode: 'default', // or 'simple'
      table: false,
      //标记页数；页码
      ipagination: {
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        total: 0
      },
      selectedRowKeysArrey: [],
      libraryData: [],
      replaceFields: {
        children: 'children',
        title: 'title',
        key: 'key',
        value: 'value'
      },
      replaceFieldsa: {
        label: 'name',
        value: 'id'
      },
      replaceFieldsb: {
        label: 'name',
        value: 'id'
      },
      shopLibrary: false,
      confirmLoading: false,
      sortLista: [],
      sortLista2: [],
      sortListab: [],
      secondary: [],
      secondaryid: '',
      shopList: [],
      inputValue: '',
      categoriesName: '',
      currentNameIndex: 0,
      currentTagIndex: -1,
      // tags: [],
      inputVisible: false,
      // table
      libraryColumns: [
        {
          align: 'center',
          title: '商品名称',
          dataIndex: 'name',
        },
        {
          title: '图片',
          align: 'center',
          dataIndex: 'picture',
          scopedSlots: { customRender: 'imgSlot' }
        },
        // {
        //   title: '属性',
        //   align: 'center',
        //   dataIndex: 'nam2e',
        // },
        // {
        //   title: '规格',
        //   align: 'center',
        //   dataIndex: 'name1',
        // },
        // {
        //   title: '操作',
        //   align: 'center',
        //   key: 'action',
        //   scopedSlots: {
        //     customRender: 'operation'
        //   }
        // }
      ],
      columns1: [

        {
          title: '属性名称',
          dataIndex: 'nameSku',
          key: 'nameSku',
          width: '30%',
          type: FormTypes.input,
          scopedSlots: { customRender: 'nameSku' },
          validateRules: [{ required: true, message: '${title}不能为空' }]
        },
        {
          title: '属性值(用@分割)',
          dataIndex: 'valueSku',
          key: 'valueSku',
          width: '55%',
          type: FormTypes.tags,
          scopedSlots: { customRender: 'tagSlot' },
          validateRules: [{ required: true, message: '${title}不能为空' }]
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: {
            customRender: 'operation'
          }
        }
      ],
      columns2: [

        {
          title: '规格名称',
          dataIndex: 'nameSku',
          key: 'nameSku',
          width: '15%',
          type: FormTypes.input,
          scopedSlots: { customRender: 'nameSku' },
          validateRules: [{ required: true, message: '${title}不能为空' }]
        },
        {
          title: '规格图片',
          dataIndex: 'pictureSku',
          key: 'pictureSku',
          width: '10%',
          scopedSlots: { customRender: 'imgSlot' }
        },
        {
          title: '会员价',
          dataIndex: 'priceSku',
          key: 'priceSku',
          width: '15%',
          type: FormTypes.input,
          scopedSlots: { customRender: 'priceSku' },
          validateRules: [{ required: true, message: '${title}不能为空' }]
        },
        {
          title: '非会员价',
          dataIndex: 'srcPriceSku',
          key: 'srcPriceSku',
          width: '15%',
          type: FormTypes.input,
          scopedSlots: { customRender: 'srcPriceSku' },
          validateRules: [{ required: true, message: '${title}不能为空' }]
        },
        {
          title: '重量(g)',
          dataIndex: 'weightGSku',
          key: 'weightGSku',
          width: '10%',
          type: FormTypes.input,
          scopedSlots: { customRender: 'weightGSku' }
        },

        {
          title: '库存',
          dataIndex: 'stockSku',
          key: 'stockSku',
          width: '10%',
          scopedSlots: { customRender: 'stockSku' }
        },
        {
          title: '打包费(元)',
          dataIndex: 'packFeeSku',
          key: 'packFeeSku',
          width: '10%',
          scopedSlots: { customRender: 'packFeeSku' }
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: {
            customRender: 'operation'
          }
        }
      ],
      goodsAttributeVoList: [],
      goodsSpecificationsVoList: [],
      sourceChannelId: '',//原频道id
      channelIdb: '',
      sourceChannelIdb: '',//原频道id
      model: {
        sort: 0,
        goodDetail: ''
      },
      // model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      chooseOrder: {},
      validatorRules: {
        /*  shopId: [
              { required: true, message: '请选择所属门店' },
          ],*/
        name: [
          { required: true, message: '请输入商品全称!' }
        ],
        shortName: [
          { required: true, message: '请输入商品简称!' }
        ],
        originalPrice: [
          { required: false, message: '请输入商品原价!' },
          { pattern: /^[1-9]\d*|0|\d+\.\d+$/, message: '请输入正确的金额!' }
        ],
        presentPrice: [
          { required: true, message: '请输入商品现价!' },
          { pattern: /^[1-9]\d*|0|\d+\.\d+$/, message: '请输入正确的金额!' }
        ],
        priceSku: [
          { required: true, message: '请输入规格售价!' },
          { pattern: /^[1-9]\d*|0|\d+\.\d+$/, message: '请输入正确的金额!' }
        ],
        weightGSku: [
          { pattern: /^[1-9]\d*$/, message: '请输入正确的重量!' }
        ],
        description: [
          { required: false, message: '请输入商品完整描述!' }
        ],
        status: [
          { required: true, message: '请选择商品上下架状态!' }
        ],

        kategorieId: [
          { required: true, message: '请选择商品分类!' }
        ],
        /*isIndex: [
          { required: true, message: '请选择是否首页展示!' }
        ],
        isHot: [
          { required: true, message: '请选择是否热门商品!' }
        ],*/
        // TODO前端增加限制
        /*oneNoDelivery: [
          { required: true, message: '请选择是否单点不送!' }
        ],*/
        visitNum: [
          { required: true, message: '请输入浏览次数!' }
        ],
        saleNum: [
          { required: true, message: '请输入销售数量!' }
        ],
        picture: [
          { required: true, message: '请上传图片!' }
        ],
        goodsSpecificationsVoList: [{
          required: true, message: '请至少添加一个规格哟!'
        }],
        sort: [
          { pattern: /^-?\d+$/, message: '请输入整数!' }
        ]
      },
      url: {
        add: '/goods/goodsBasic/add',
        edit: '/goods/goodsBasic/edit',
        queryById: '/goods/goodsBasic/queryById',
        goodsAttributeVoListUrl: '/goods/goodsAttribute/getGoodsAttributeDataByGoodsId',
        goodsSpecificationsVoListUrl: '/goods/goodsSpecifications/getGoodsSpecificationsDataByGoodsId',
        getShopListUrl: '/shop/shopBasic/selectShopList',
        shopChangeUrl: '/goods/goodsSort/querySortsByShopId',
        addSort: '/goods/goodsSort/add',
        getGoods: '/goods/goodsHub/page',
        getGoodsList: '/goods/goodsHub/getGoodsHubList'
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  created() {
    this.library = localStorage.getItem("library")
    if (this.library == 1) { //商品库引用
      this.url.edit = "/goods/goodsHub/editGoodsHub"
      this.url.add = "/goods/goodsHub/addGoodsHub"
      this.url.shopChangeUrl = '/shopType/getTree'
    }
    console.log(this.$store.state.user.info, "获取当前登录用户");
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    handleTreeSelectChange(value) {
      // 处理选中值的变化
      console.log('选中的值:', value);
      this.secondaryid = value
      this.secondaryrequest()
    },
    uploadImg(file, insertFn) {
      let imgData = new FormData();
      imgData.append('file', file);
      //调接口，上传图片
      return new Promise((resolve, reject) => {
        uploadAction('/sys/common/upload', imgData)
          .then(response => {
            if (response.code == 0) {
              resolve(response.message);
            } else {
              reject(response.message);
            }
          })
          .catch(error => {
            reject(error);
          });
      })
        .then(url => {
          insertFn(url);
        })
        .catch(error => {
          // 处理错误
        });
    },

    //富文本
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    getList() {
      this.table = true
      getAction(this.url.getGoods).then(res => {
        this.libraryData = res.result.records
        if (res.success) {
          this.table = false
        }
        console.log(res)
      })
    },
    changePage(pagination) {
      this.queryParam.pageNo = pagination.current;
      this.queryParam.pageSize = pagination.pageSize;
    },
    // 选中一行 
    onSelectChange(a, b) {
      this.selectedRowKeysArrey = a;
      this.chooseOrder = b[0];
      console.log(this.chooseOrder, "选中的数据");
    },
    showLibrary() {
      this.shopLibrary = true
      this.getList()
    },
    shopLibraryOk() {
      if (this.chooseOrder.id) {
        this.model = this.chooseOrder
        this.model.names = this.chooseOrder.name
        this.model.shopId = this.$store.state.user.info.currentSelectedShopId
        this.getGoodsInfoVoList(this.model.id)
        this.shopLibrary = false
      }
    },
    shopLibraryCancel() {
      this.shopLibrary = false
    },
    secondaryrequest() {
      let that = this
      getAction('/goodKategorie/mkGoodsKategorie/list', { topId: this.secondaryid }).then(res => {
        if (res.success) {
          that.secondary = res.result.records
          console.log(this.secondary, 11111)
        }
      })
    },
    shopChangea(shopId) {
      console.log(shopId)
      let that = this
      this.sortLista = []
      this.sortLista2 = []
      getAction('/goodKategorie/mkGoodsKategorie/list', { topId: '0' }).then(res => {
        if (res.success) {
          // res.result.forEach((e) => {
          //   e['selectable'] = false;
          // })
          that.sortLista = res.result.records
          console.log(this.sortLista, 11111)
        }
      })



      getAction('/goods/goodsSort/getList', { shopId: store.getters.userInfoCurrentShop.id }).then(res => {
        if (res.success) {
          that.sortLista2 = res.result
          console.log(this.sortLista2, 11111)
        }
      })

    },
    shopChangeb(shopId) {
      console.log(shopId)
      let that = this
      this.sortListb = []
      getAction('/goodBrand/list').then(res => {
        if (res.success) {
          // res.result.forEach((e) => {
          //   e['selectable'] = false;
          // })
          that.sortListb = res.result.records
          console.log(this.sortListb, 11111)
          that.channelIdb = ''
          getAction('/goodBrand/queryById', { id: this.model.id }).then(ress => {
            console.log(ress.result)
            that.channelIdb = ress.result
            that.sourceChannelIdb = ress.result
          })
        }
      })

    },
    getShopListUrl() {
      this.shopList = []
      getAction(this.url.getShopListUrl).then(res => {
        if (res.success) {
          let result = res.result
          result.forEach((e) => {
            this.shopList.push(e)
          })
        }
      })
      console.log(this.shopList)

    },
    /*   handleClose(removedTag) {

           const tagVo = this.goodsAttributeVoListUrl[index].valueSku.split(",")
           const tags = tagVo.filter(tag => tag !== removedTag);
           console.log(tags);
           this.tags = tags;
           this.goodsAttributeVoListUrl[index].valueSku = tags
       },*/
    //删除路由条件配置项
    removeTag(item, removedTag) {
      const tags = item.valueSku.filter(tag => tag !== removedTag)
      item.valueSku = tags
    },
    /* //添加路由选项
     predicatesHandleMenuClick(e) {
         console.log(e)
         this.router.predicates.push({
             valueSku: [],
             name: e.key+1
         })
     },*/
    editTag(tag, index) {
      this.currentTagIndex = index
    },

    //显示输入框
    showInput(item, index) {
      this.inputVisible = true
      this.currentNameIndex = index
    },

    //输入框确认
    handleInputEditConfirm(item, tag, index) {
      if (this.inputValue) {
        const inputValue = this.inputValue
        item.valueSku[index] = inputValue
      }
      this.currentTagIndex = -1

    },
    //路由选项输入框失去焦点事件
    handleInputChange(e) {
      this.inputValue = e.target.value
    },
    //输入框确认
    handleInputConfirm(item) {
      const inputValue = this.inputValue
      let tags = item.valueSku
      if (inputValue && tags.indexOf(inputValue) === -1) {
        item.valueSku = [...tags, inputValue]
      }
      console.log(tags)
      Object.assign(this, {
        tags,
        inputVisible: false,
        inputValue: ''
      })
      this.currentTagIndex = -1
    },
    getGoodsInfoVoList(id) {
      // console.log("in")
      this.goodsAttributeVoList = []
      getAction(this.url.goodsAttributeVoListUrl + '/' + id).then(res => {
        if (res.success) {
          let result = res.result
          result.forEach((e) => {
            delete e.id
            this.goodsAttributeVoList.push(e)
          })
        }
      })
      console.log(this.goodsAttributeVoList);
      this.model.goodsAttributeVoList = this.goodsAttributeVoList
      this.goodsSpecificationsVoList = []
      getAction(this.url.goodsSpecificationsVoListUrl + '/' + id).then(res => {
        if (res.success) {
          let result = res.result
          result.forEach((e) => {
            delete e.id
            this.goodsSpecificationsVoList.push(e)
          })
        }
      })
      // console.log(this.goodsSpecificationsVoList);
      this.model.goodsSpecificationsVoList = this.goodsSpecificationsVoList
    },
    newMember1() {
      this.goodsAttributeVoList.push({
        key: 'key' + this.goodsAttributeVoList.length + 1,
        nameSku: '',
        valueSku: '',
        editable: true,
        isNew: true
      })
    },
    remove1(key) {
      const newData = this.goodsAttributeVoList.filter(item => item.key !== key)
      this.goodsAttributeVoList = newData
    },
    saveRow1(key) {
      // check
      let target = this.goodsAttributeVoList.filter(item => item.key === key)[0]
      if (target.nameSku == '' || target.valueSku == '') {
        this.$message.error('属性名称和属性值都不能为空哟~')
        return
      }
      target.editable = false
      target.isNew = false
    },
    toggle1(key) {
      let target = this.goodsAttributeVoList.filter(item => item.key === key)[0]
      if (target.nameSku == '' || target.valueSku == '') {
        this.$message.error('属性名称和属性值都不能为空哟~')
        return
      }
      target.editable = !target.editable
    },
    cancel1(key) {
      let target = this.goodsAttributeVoList.filter(item => item.key === key)[0]
      target.editable = false
    },
    handleChange1(value, key, column) {

      const newData = [...this.goodsAttributeVoList]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target[column] = value
        this.goodsAttributeVoList = newData
      }
    },
    newMember2() {
      this.goodsSpecificationsVoList.push({
        key: 'key' + this.goodsSpecificationsVoList.length + 1,
        nameSku: '',
        // pictureSku: '',
        priceSku: '',
        weightGSku: 500,
        stockSku: '9999',
        packFeeSku: '0.00',
        editable: true,
        isNew: true
      })
    },
    remove2(key) {
      const newData = this.goodsSpecificationsVoList.filter(item => item.key !== key)
      this.goodsSpecificationsVoList = newData
    },
    saveRow2(key) {
      let target = this.goodsSpecificationsVoList.filter(item => item.key === key)[0]
      if (target.nameSku == '' || target.priceSku == '') {
        this.$message.error('属性名称和售价都不能为空哟~')
        return
      }

      const reg = /^[1-9]\d*|0|\d+\.\d+$/
      if (reg.test(target.priceSku)) {
        target.editable = false
        target.isNew = false
      } else {
        this.$message.error('请输入正确的金额(0.01)')
        return
      }
    },
    toggle2(key) {
      //编辑
      let target = this.goodsSpecificationsVoList.filter(item => item.key === key)[0]
      if (target.nameSku == '' || target.priceSku == '') {
        this.$message.error('属性名称和售价都不能为空哟~')
        return
      }

      const reg = /^[1-9]\d*|0|\d+\.\d+$/
      if (reg.test(target.priceSku)) {
        target.editable = !target.editable
      } else {
        this.$message.error('请输入正确的金额')
        return
      }

    },
    cancel2(key) {
      let target = this.goodsSpecificationsVoList.filter(item => item.key === key)[0]
      target.editable = false
    },
    handleChange2(value, key, column) {
      const newData = [...this.goodsSpecificationsVoList]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target[column] = value
        this.goodsSpecificationsVoList = newData
      }
    },
    add() {
      this.shopChangea()
      // this.shopChangeb()
      this.model = Object.assign({}, null)

      this.visible = true
    },
    edit(record) {
      console.log(record)
      // this.shopChangea()
      // this.shopChangea(record.shopId)
      this.shopChangeb(record.shopId)
      this.$nextTick(() => {
        this.model = Object.assign({}, record)
        this.getGoodsInfoVoList(this.model.id)
      })
      this.visible = true
      // this.shopChangea(record.shopId)
      this.shopChangea()
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (this.chooseOrder.id) {
            delete this.model.id
          }
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
            this.model.goodBrand = localStorage.getItem('myDataId')
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          this.model.goodsAttributeVoList = this.goodsAttributeVoList
          this.model.goodsSpecificationsVoList = this.goodsSpecificationsVoList
          this.model.sorts = '1'
          this.model.enableGroup = '1'

          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              postAction('/goodsChannelShip/goodBindChannels', {
                channelIds: that.channelId,
                goodId: res.result.id,
                sourceChannelId: that.sourceChannelId
              }).then(ress => {
                console.log(ress)
              })
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })


        }

      })
    },
    uploadImgs(path, index) {
      this.goodsSpecificationsVoList[index].pictureSku = path
      // console.log(this.goodsSpecificationsVoList)
    }
  }
}
</script>